package cn.jsp.spring.dao;

import cn.jsp.spring.domain.Product;
import cn.jsp.spring.domain.Stu;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ProductDao {
  @Autowired
  DataSource dataSource;
  @SneakyThrows
  public List<Product> query(String sql,Object...params){
    //进行数据库查询，封装为一个对象
    List<Product> res=new ArrayList<>();
    try (Connection con = dataSource.getConnection();
         PreparedStatement pstmt = con.prepareStatement(sql);
         ResultSet rs = pstmt.executeQuery()) {
      while (rs.next()) {
        //把ResultSet中的一行转变为Product ResultSet->Product
        Product product=new Product();
        product.setName(rs.getString("name"));
        product.setPrice(rs.getDouble("price"));
        res.add(product);
      }
    }
    return res;
  }
}
